package com.rgs.module.login.controller;

import cn.hutool.core.util.IdUtil;
import com.google.code.kaptcha.Producer;
import com.google.common.io.BaseEncoding;
import com.rgs.base.core.model.WebApiReturnResultModel;
import com.rgs.base.core.system.WebResponseState;
import com.rgs.module.login.bo.CaptchaImageBO;
import com.rgs.module.login.service.LoginCacheService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author Ren Gaoshuai
 * @ClassName CaptchaController
 * @date 2022-03-02 17:01
 **/
@Api(tags = "验证码接口")
@RestController
@RequestMapping("/v1")
public class CaptchaController {

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Resource
    LoginCacheService loginCacheService;


    @ApiOperation(value = "获取验证码")
    @GetMapping("/captchaImage")
    public WebApiReturnResultModel<CaptchaImageBO> captchaImage(){
        String uuid = IdUtil.fastSimpleUUID();
        String capStr = null,code = null;

        BufferedImage image = null;

        //生成验证码 格式 5+8=?@13
        String capText = captchaProducerMath.createText();
        capStr = capText.substring(0, capText.lastIndexOf("@"));
        code = capText.substring(capText.lastIndexOf("@") + 1);
        image = captchaProducerMath.createImage(capStr);

        //存入redis
        loginCacheService.captchaPut(uuid,code);

        //输出验证码图片
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image,"jpg",os);
        } catch (IOException e) {
            return WebApiReturnResultModel.of(
                    WebResponseState.CAPTCHA_ERROR,
                    e.getMessage(),
                    new CaptchaImageBO());
        }
        return  WebApiReturnResultModel.ofSuccess(
                CaptchaImageBO.builder()
                        .uuid(uuid)
                        .imageBase64(BaseEncoding.base64().encode(os.toByteArray()))
                        .build());
    }
}
